package com.example.knowman.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.knowman.ReturnMessage.Message;
import com.example.knowman.dao.knowMainEx;
import com.example.knowman.dao.knowMainEx9_5ByPeriod;
import com.example.knowman.entity.knowArchFiles;
import com.example.knowman.entity.knowCategory;
import com.example.knowman.entity.knowMain;
import com.example.knowman.entity.labelCategory;
import com.example.knowman.mapper.KnowArchFilesMapper;
import com.example.knowman.mapper.KnowCategoryMapper;
import com.example.knowman.mapper.KnowMainMapper;
import com.example.knowman.mapper.StaffListMapper;
import com.example.knowman.service.IKnowCategoryService;
import com.example.knowman.service.IKnowMainService;
import com.example.knowman.service.IStaffListService;
import com.example.knowman.service.IknowArchFilesService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class KnowArchFilesServiceImpl extends ServiceImpl<KnowArchFilesMapper, knowArchFiles> implements IknowArchFilesService {


    @Override
    public List<knowArchFiles> getByKnowId(Integer knowId) {
        return this.lambdaQuery().select().eq(knowArchFiles::getKnowId,knowId).list();
    }

    @Override
    public Message insertItems(knowArchFiles item) {
        Message message = new Message();
        try{

            this.save(item);

            message.setCode(200);
            message.setTip("导入文件成功");
        }catch (Exception e){
            message.setCode(100);
            message.setTip("导入文件失败");
        }

        return message;

    }

    @Override
    public void downloadFile(String fileUrl, HttpServletResponse response) {
        try {
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            InputStream inputStream=conn.getInputStream();
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //以Post方式提交表单，默认get方式
            ServletOutputStream out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            log.error("下载成功！");
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件失败！");
        }
    }

    @Override
    public void AddDCount(Integer archFilesId) {
        knowArchFiles temp = this.lambdaQuery().select().eq(knowArchFiles::getArchFilesId,archFilesId).one();
        Integer count = temp.getDownloadCount()+1;

        this.lambdaUpdate().eq(knowArchFiles::getArchFilesId,archFilesId).set(knowArchFiles::getDownloadCount,count).update();
    }

    @Override
    public void Upload(MultipartFile file, Integer knowId, String staffCode) {
        if(file == null){

        }
        else{
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取不含后缀的文件名
            String filenameWithoutExtension = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            // 获取文件大小
            long size = file.getSize();
            String res ="";
            DecimalFormat dec = new DecimalFormat("0.00");
            //处理大小
            double tempSize = (double) size;
            Integer level =0;
            while (tempSize>1024){
                tempSize/=1024.0;
                level++;
            }
            if(level==0){
                res = dec.format(tempSize).concat(" B");
            }
            else if(level==1){
                res = dec.format(tempSize).concat(" KB");
            }
            else if(level==2){
                res = dec.format(tempSize).concat(" MB");
            }
            else if(level==3){
                res = dec.format(tempSize).concat(" GB");
            }
            else if(level==4){
                res = dec.format(tempSize).concat(" TB");
            }
            else {
                res="文件过大";
            }
            // 打印文件信息
//            System.out.println("原始文件名: " + originalFilename);
//            System.out.println("不含后缀的文件名: " + filenameWithoutExtension);
//            System.out.println("文件大小: "+ res);
            String newFilename = staffCode + originalFilename;
            knowArchFiles item = new knowArchFiles();
            //这个url是保存进数据库的，到时候部署到服务器要改
            String URL = "http://124.223.214.155:81/files/Know/"+newFilename;
            //参考ip: http://localhost:81/files/   #http://124.223.214.155:81/files/
            item.setFileURL(URL);
            item.setKnowId(knowId);
            item.setFileSize(res);
            item.setFileName(originalFilename);


            //上传文件到服务器
//        File dest = new File("C:\\Users\\Administrator\\Desktop\\Files\\Know\\" + newFilename);
            File dest = new File("/home/digitalArch/Files/Know/" + newFilename);
            //上面的路径到时候也要进行修改，参考uploadPath: D:\\data\Files\     #/home/digitalArch/Files/  后面估计还有Know这个文件夹路径
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                e.printStackTrace();

            }

            //写入数据库
            this.insertItems(item);
        }

    }

    @Override
    public Message deleteByarchFilesId(Integer archFilesId) {
        Message message = new Message();
        QueryWrapper<knowArchFiles> wrapper = new QueryWrapper<>();
        wrapper.eq("\"archFilesId\"",archFilesId);
        try{
            this.remove(wrapper);
            message.setCode(200);
            message.setTip("删除成功");
        }catch (Exception e){
            message.setCode(100);
            message.setTip("删除失败");
        }

        return message;
    }


}
